package logic

import (
	"errors"
	"sems/config"
	"sems/dao"
	"sems/model"
	"sems/util/encryptPassword"
	"time"

	"go.uber.org/zap"
)

var Size = 4

// GetTotalPages 计算总页码
func GetTotalPages(count int64) int64 {
	return (count + int64(Size) - 1) / int64(Size)
}

func CheckUser(username string) (user model.User, err error) {
	return dao.CheckUser(username)
}

func SaveUser(username string, password string) (err error) {
	avatar := config.DefaultAvatarURL
	//需要对密码做加密处理
	pwd := encryptPassword.BcryptHash(password)
	user := model.User{
		Username:   username,
		Password:   pwd,
		Avatar:     avatar,
		Role:       "user",
		CreateTime: time.Now(),
		Status:     "正常",
	}

	if err = dao.SaveUser(user); err != nil {
		zap.L().Error("用户注册失败")
		errors.New("用户注册失败")
		return err
	}
	return nil
}

func GetUsers(username string, currentPage int) (users []model.User, list *model.PaginationList, err error) {
	if currentPage <= 0 {
		currentPage = 1
	}
	offset := (currentPage - 1) * Size
	var count int64
	users, count, err = dao.GetUsers(username, Size, offset)
	if err != nil {
		zap.L().Error("查询用户列表出错了", zap.Error(err))
		err = errors.New("查询用户列表出错了")
		return
	}
	totalPages := GetTotalPages(count)
	if currentPage > int(totalPages) {
		currentPage = int(totalPages)
	}
	list = &model.PaginationList{
		Count:       count,
		TotalPages:  totalPages,
		CurrentPage: currentPage,
		Size:        Size,
	}
	return users, list, nil
}

func GetUserInfo(userId int) (user model.User, err error) {
	return dao.GetUserInfo(userId)
}

func EditUserRole(userId int, role string) (err error) {
	user := model.User{
		Role: role,
	}
	if err = dao.EditUser(userId, user); err != nil {
		zap.L().Error("修改用户权限失败")
		return errors.New("修改用户权限失败")
	}
	return nil
}

func EditUser(userId int, username string, phone string, avatar string) (err error) {
	user := model.User{
		Username: username,
		Avatar:   avatar,
		Phone:    phone,
	}
	if err = dao.EditUser(userId, user); err != nil {
		zap.L().Error("修改用户信息失败")
		return errors.New("修改用户信息失败")
	}
	return nil
}

func EditUserPassword(userId int, oldPassword, newPassword string) (err error) {
	u, err := dao.GetUserInfo(userId)
	if err != nil {
		zap.L().Error("查询用户信息出错")
		err = errors.New("查询用户信息出错")
		return err
	}
	if !encryptPassword.BcryptCheck(oldPassword, u.Password) {
		zap.L().Error("原始密码不正确")
		err = errors.New("原始密码不正确")
		return err
	}
	user := model.User{
		Password: encryptPassword.BcryptHash(newPassword),
	}
	if err = dao.EditUser(userId, user); err != nil {
		zap.L().Error("修改用户密码失败")
		err = errors.New("修改用户密码失败")
		return err
	}
	return nil
}
